from django.utils.deprecation import MiddlewareMixin
from web import models
from django.conf import settings
from django.shortcuts import redirect
import datetime


# 面向对象,通过中间件来增加request的功能
class Tracer(object):

    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None


class AuthMiddleware(MiddlewareMixin):

    def process_request(self, request):
        # 判断session里是否有值
        request.tracer = Tracer()
        user_id = request.session.get('user_id', 0)
        user_object = models.UserInfo.objects.filter(id=user_id).first()

        request.tracer.user = user_object

        # 获取白名单(用于查询是否登陆状态)

        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            # 默认返回none
            return
        if not request.tracer.user:
            return redirect('login')

        # 获取用户数据的支付信息(普通用户)
        _object = models.Transaction.objects.filter(user=user_object, status=2).order_by('-id').first()

        # 判断是否已过期
        current_datetime = datetime.datetime.now()
        # 是否是免费版的(obj.end_datetime为空也是免费版),或vip过期

        if _object.end_datetime and _object.end_datetime < current_datetime:
            _object = models.Transaction.objects.filter(user=user_object, status=2, price_policy__category=1).first()

        request.tracer.price_policy = _object.price_policy

    def process_view(self, request, *args, **kwargs):
        if not request.path_info.startswith('/manage/'):
            return
        project_id = args[2].get('project_id')
        project_object = models.Project.objects.filter(creator=request.tracer.user, id=project_id).first()
        if project_object:
            # 是我创建的项目
            request.tracer.project = project_object
            return
        project_user_object = models.ProjectUser.objects.filter(user=request.tracer.user, project_id=project_id).first()
        if project_user_object:
            # 如果是我参与的项目
            request.tracer.project = project_user_object.project

            return

        return redirect('project_list')
